package com.cxria.pattern.interpreter

class Calculator {

    private Expression expression

    Calculator(String expStr) {
        Stack<Expression> stack = new Stack<>()
        char[] charArray = expStr.toCharArray()
        Expression left
        Expression right
        for(i in 0..charArray.length - 1){
            switch(charArray[i]){
                case '+':
                    left = stack.pop()
                    right = new VarExpression(String.valueOf(charArray[++i]))
                    stack.push(new AddExpression(left, right))
                    break
                case '-':
                    left = stack.pop()
                    right = new VarExpression(String.valueOf(charArray[++i]))
                    stack.push(new SubExpression(left, right))
                    break
                default:
                    stack.push(new VarExpression(String.valueOf(charArray[i])))
            }
        }
        expression = stack.pop()
    }

    int run(Map<String, Integer> var){
        expression.interpreter(var)
    }

}
